package com.epam.tcs.actions.pages;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.ObjectNotFoundException;

import com.epam.tcs.actions.BreadCrumb;
import com.epam.tcs.actions.Paging;
import com.epam.tcs.dao.factory.DAO;
import com.epam.tcs.dao.factory.StudentDAO;
import com.epam.tcs.dao.hibernate.entities.Group;
import com.epam.tcs.dao.hibernate.entities.Student;

public class StudentPage extends PageAbstract{
	
	@Override
	public void doExec(HttpServletRequest req, HttpServletResponse res) {
		
		String target = req.getRequestURI().substring(
				req.getContextPath().length());

		String[] tarr = target.split("/");
	
		BreadCrumb.add(req, res, "Студенты", "/tcs/student");
		try {
			if ((tarr.length == 4) && tarr[3].equals("add")) {
				addStudent(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("del")) {
				delStudent(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("edit")) {
				editStudent(req, res);
			} else {
				listStudents(req, res);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void editStudent(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		if (req.getParameter("student_id") != null
				&& Integer.parseInt(req.getParameter("student_id")) > 0) {
			DAO<Student> student = dao.getStudentDAO();
			try {
				Student s = student.getElement(Integer.parseInt(req
						.getParameter("student_id")));
				BreadCrumb.add(req, res,
						"Изменить студента " + s.getFirstName(),
						"/tcs/student/edit?student_id=" + s.getStudent_id());
				DAO<Group> group = dao.getGroupDAO();
				if (req.getMethod() == "POST" && this.validateStudentForm(req)) {
					s.setGroup((Group) group.getElement(Long.parseLong(req
							.getParameter("group"))));
					s.setLastName(req.getParameter("lastname"));
					s.setFirstName(req.getParameter("firstname"));
					s.setMiddleName(req.getParameter("middlename"));

					SimpleDateFormat bdf = new SimpleDateFormat("dd.MM.yyyy");
					try {
						s.setBirthday(bdf.parse(req.getParameter("birthday")));
					} catch (ParseException e) {
						e.printStackTrace();
					}

					s.setEmail(req.getParameter("email"));
					s.setPhone(req.getParameter("phone"));

					try {
						student.updateElement(s);
						req.setAttribute(
								"message",
								"Студент \"" + s.getLastName() + " "
										+ s.getFirstName() + "\" изменен.");
					} catch (Exception e) {
						req.setAttribute("message",
								"Попытка изменить студента вызвала исключение: "
										+ e.getMessage());
					}
				}
				req.setAttribute("widget", "edit_student");
				req.setAttribute("action",
						"/tcs/student/edit?student_id=" + s.getStudent_id());
				req.setAttribute("student", s);
				req.getSession().setAttribute("listGroups",
						group.getAllElements());

				outputPage("student/student_form.jsp", req, res);

			} catch (ObjectNotFoundException e) {
				res.sendRedirect(req.getContextPath() + "/tcs/student/add");
			}
		}
	}

	private void delStudent(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		DAO<Student> student = dao.getStudentDAO();
		ArrayList<String> students_name = new ArrayList<String>();
		for (Enumeration<String> e = req.getParameterNames(); e
				.hasMoreElements();) {
			String[] s = ((String) e.nextElement()).split("_");
			Student student_element = (Student) student.getElement(Long
					.parseLong(s[2]));
			students_name.add(student_element.getLastName() + " "
					+ student_element.getFirstName());
			student.deleteElement(student.getElement(Long.parseLong(s[2])));
		}
		req.setAttribute("widget", "student");
		req.setAttribute("message",
				"Удалены студенты: " + students_name.toString());
		req.getSession().setAttribute("listStudents", student.getAllElements());
		outputPage("student/student.jsp", req, res);
	}

	private void listStudents(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		StudentDAO student = (StudentDAO) dao.getStudentDAO();
		req.setAttribute("widget", "student");
		req.setAttribute("pageElements", Paging.getPageElements(
				student.getTotalElements(), "/tcs/student"));

		if (req.getParameter("page") != null
				&& Integer.parseInt(req.getParameter("page")) > 1) {
			int page = Integer.parseInt(req.getParameter("page"));
			req.getSession().setAttribute(
					"listStudents",
					student.getRangeElements((page - 1) * Paging.COUNT,
							Paging.COUNT));
		} else {
			req.getSession().setAttribute("listStudents",
					student.getRangeElements(0, Paging.COUNT));
		}

		outputPage("student/student.jsp", req, res);
	}

	private void addStudent(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		BreadCrumb.add(req, res, "Добавить студента", "/tcs/student/add");
		DAO<Group> group = dao.getGroupDAO();
		if (req.getMethod() == "POST" && this.validateStudentForm(req)) {
			DAO<Student> student = dao.getStudentDAO();
			Student s = new Student();
			s.setGroup((Group) group.getElement(Long.parseLong(req
					.getParameter("group"))));
			s.setLastName(req.getParameter("lastname"));
			s.setFirstName(req.getParameter("firstname"));
			s.setMiddleName(req.getParameter("middlename"));

			SimpleDateFormat bdf = new SimpleDateFormat("dd.MM.yyyy");
			try {
				s.setBirthday(bdf.parse(req.getParameter("birthday")));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			s.setEmail(req.getParameter("email"));
			s.setPhone(req.getParameter("phone"));

			if (student.addElement(s) != 0L) {
				req.setAttribute("message", "Студент \"" + s.getLastName()
						+ " " + s.getFirstName() + "\" успешно добавлен.");
			}
		}
		req.setAttribute("widget", "add_student");
		req.setAttribute("action", "/tcs/student/add");
		req.getSession().setAttribute("listGroups", group.getAllElements());
		outputPage("student/student_form.jsp", req, res);
	}


	private boolean validateStudentForm(HttpServletRequest req) {

		return true;
	}
}
